package com.suixiang.wx.enterprise.suite.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * druid数据源配置
 * 
 * @author wzx
 *
 */

@Configuration
public class DruidConfig {

	@Value("${spring.datasource.druidLoginName}")
	private String druidLoginName;
	@Value("${spring.datasource.druidLoginPassword}")
	private String druidLoginPassword;

	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druid() {
		return new DruidDataSource();
	}

	/**
	 * 向容器添加状态视图servlet
	 * 
	 * @return
	 */
	@Bean
	public ServletRegistrationBean<Servlet> statViewServlet() {
		ServletRegistrationBean<Servlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
		Map<String, String> map = new HashMap<>();
		map.put("loginUsername", druidLoginName);
		map.put("loginPassword", druidLoginPassword);
		map.put("allow", "");// 默认允许所有访问
		bean.setInitParameters(map);
		return bean;
	}

	/**
	 * 向容器添加web状态过滤器
	 * 
	 * @return
	 */
	@Bean
	public FilterRegistrationBean<Filter> webStatFilter() {
		FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
		bean.setFilter(new WebStatFilter());
		Map<String, String> map = new HashMap<>();
		map.put("exclusions", "*. js ,*. gif ,*. jpg ,*. png ,*. css ,*. ico ,/druid/*");
		bean.setInitParameters(map);
		bean.setUrlPatterns(Arrays.asList("/*"));
		return bean;
	}

}
